package server

import (
	"context"
	"errors"
	"longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/common/payment/client"
	"longmen/server/pkg/db/mysql/db_main"
	pb "longmen/server/pkg/protobuf"
)

/**
 * @Description //慧收钱
 **/
func (s *Server) ApplyAliPayment(ctx context.Context, req *pb.OrderNoReq) (*pb.HsqBusinessResp, error) {
	orderNo, _ := util.CreatePaymentOrderNo(_const.PAYMENT_PREFIX_ALI)
	payChannel := _const.PAY_CHANNEL_ALPAY
	//终端类型
	switch req.Terminal {
	case 0:
		req.Terminal = _const.TERMINAL_ANDROID
	case 1:
		req.Terminal = _const.TERMINAL_APPLE
	default:
		req.Terminal = _const.TERMINAL_PC
	}
	if db_main.InsertAndroidPaymentApply(req, orderNo, int(req.Terminal), payChannel) > 0 {
		if paymentApply, err := db_main.GetPaymentOrderNo(int(req.UserId), orderNo); err == nil {
			if api := GetPaymentApi(_const.PAYMENT_ALI_CODE); api != nil {
				return client.AliPay(api, paymentApply)
			}
		}
	}
	return nil, errors.New("申请充值失败")
}

/**
 * @Author willi
 * @Description //TODO
 * @Date 14:12 2022/9/5
 * @Param
 * @return
 **/

func (s *Server) AliPaymentCallBack(ctx context.Context, hsqReq *pb.AliPayCallBackReq) (*pb.HsqPaymentCallBackResp, error) {
	ret := &pb.HsqPaymentCallBackResp{Code: _const.RPC_FAILED}
	if api := GetPaymentApi(_const.PAYMENT_HSQ_CODE); api != nil {
		if paymentApply := client.AliPayCallBack(hsqReq.Params); paymentApply != nil {
			productPayReq := createAilProductPayReq(paymentApply)
			product := commitPayOrder(_const.PAY_SUCCESS, productPayReq)
			ret.Code = product.Code
		} else {
			productPayReq := createAilProductPayReq(paymentApply)
			product := commitPayOrder(_const.PAY_FAIL, productPayReq)
			ret.Code = product.Code
		}
	}
	return ret, nil
}

func createAilProductPayReq(payment *pb.PaymentApply) *pb.ProductPayReq {
	productPayReq := &pb.ProductPayReq{}
	productPayReq.TransactionId = payment.OrderNo
	productPayReq.UserId = payment.UserId
	productPayReq.OrderNo = payment.OrderNo
	productPayReq.OrderAmt = int64(payment.Price)
	return productPayReq
}
